import {ModalForm, ProFormSelect, ProFormText} from "@ant-design/pro-components";
import IHttp, {IAxiosResponse} from "@/services/http.service";
import React, {useEffect} from "react";
import {Form, message} from "antd";
import { firstValueFrom } from "rxjs"

type CreateFormProps = {
  name: string
  type: number
}

type IProps = {
  item: API.AccountItem | undefined
  onCancel: () => void
  onRefreshTable: () => void
}

export default function AccountCreateForm({item, onCancel, onRefreshTable}: IProps) {
  const [form] = Form.useForm<CreateFormProps>();
  const open = Boolean(item)
  useEffect(() => {
    if (open) {
      form.setFieldsValue({name: item?.name, type: item?.type})
    }
  }, [open])
  return (
    <ModalForm<CreateFormProps>
      width={360}
      open={open}
      form={form}
      title={item?.id ? "编辑账号" : "新建账号"}
      // trigger={
      //   <Button type="primary">添加</Button>
      // }
      onFinish={async (values) => {
        console.log(values);
        let res: IAxiosResponse | undefined = undefined
        if (item?.id) {
          res = await firstValueFrom(IHttp.updateAccount(item.id, values))
        } else {
          res = await firstValueFrom(IHttp.createAccount(values))
        }
        if (res?.status) {
          message.success(item?.id ?  "更新成功" : "创建成功")
          onRefreshTable()
        }

        // message.success('提交成功');
        // 不返回不会关闭弹框
        // return true;
      }}
      modalProps={{
        destroyOnClose: true,
        onCancel,
        maskTransitionName:"ant-fade",
        transitionName: "ant-fade",
      }}
    >
      <ProFormText
        name="name"
        label="账号名称"
        tooltip="最长为 24 位"
        placeholder="请输入名称"
        rules={[
          {required: true}
        ]}
      />
      <ProFormSelect
        request={async () => {
          let res = await IHttp.getAccountTypeVars().toPromise()
          return (res?.data || []).map((e: any) => {
            return {label: e.name, value: e.type}
          })
        }}
        name="type"
        label="账号平台"
        rules={[
          {required: true}
        ]}
      />
    </ModalForm>
  )
}
